package com.acme.bankapp.domain.bank.account;

import com.acme.bankapp.domain.bank.exception.NotEnoughFundsException;
import com.acme.bankapp.domain.bank.exception.OverDraftLimitExceededException;

public class CheckingAccount extends AbstractAccount {

    private int overdraft;
    private final int maxOverdraft;

    public CheckingAccount(int balance, int overdraft) {
        super(balance);
        if (overdraft < 0)
            throw new IllegalArgumentException("Overdraft must be more than zero");
        this.maxOverdraft = overdraft;
        this.overdraft = overdraft;
    }

    @Override
    protected void addMoney(int x) {
        overdraft += (maxOverdraft > overdraft ? (x > (maxOverdraft - overdraft) ? maxOverdraft - overdraft : x) : 0);
        super.addMoney(maxOverdraft > overdraft ? (x > (maxOverdraft - overdraft) ? x - (maxOverdraft - overdraft) : 0) : x);
    }

    @Override
    protected void checkToSubtractMoney(int money) throws NotEnoughFundsException {
        if (overdraft + getMoney() < money)
            throw new OverDraftLimitExceededException(this);
    }

    @Override
    protected void subtractMoney(int money) {
        int b = getMoney();
        overdraft -= b < money ? money - b : 0;
        super.subtractMoney(b < money ? b : money);
    }

    @Override
    public String toString() {
        return "accounttype=c;balance=" + getMoney() + ";overdraft=" + getOverdraft() + ";";
    }

    public int getOverdraft() {
        return overdraft;
    }
}
